package org.gitos.cloud.server.service;

import org.gitos.cloud.domain.server.User;
import org.gitos.cloud.util.CommonKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService {

    @Autowired
    JdbcTemplate jdbctemplate;

    /**
     * 第三方登录用户注册,头像和昵称随第三方变化，返回用户对象
     */
    public Object saveThirdPartyUser(String openid, String nickname,
                                     byte[] headimg, int gender, String from) {
        if (openid == null) {
            return "第三方用户唯一标识不能为空";
        }
        int update = jdbctemplate.update("update user set nickname='"
                + nickname + "',headimg=? where openid='"
                + openid + "'", new Object[]{headimg});
        if (update <= 0) {
            if (nickname == null) {
                return "帐号注册时，用户昵称不能为空";
            }
            headimg = headimg == null ? new byte[]{} : headimg;
            jdbctemplate
                    .update("insert into user (uuid,openid,nickname,headimg,gender,create_time,login_time,come_from) values ('"
                            + CommonKit.createUuid()
                            + "','"
                            + openid
                            + "','"
                            + nickname
                            + "',?,"
                            + gender
                            + ",now(),now(),'" + from + "')", new Object[]{headimg});
        }
        List<User> users = jdbctemplate.query(
                "select * from user where openid=?",
                new Object[]{openid}, new User());
        return getOne(users);
    }

    /**
     * 本地用户注册
     */
    public Object saveLocalUser(String username, String password,
                                String nickname, byte[] headimg, int gender) {
        if (username == null) {
            return "用户名不能为空";
        }
        List<User> users = jdbctemplate.query(
                "select * from user where username=?", new Object[]{username},
                new User());
        if (users.size() > 0) {
            return "用户已被注册";
        }
        if (nickname == null) {
            return "用户昵称不能为空";
        }
        if (password == null) {
            return "密码不能为空";
        }
        String uuid = CommonKit.createUuid();
        headimg = headimg == null ? new byte[]{} : headimg;
        jdbctemplate
                .update("insert into user (uuid,username,password,nickname,headimg,gender,create_time,login_time) values ('"
                        + uuid
                        + "','"
                        + username
                        + "','"
                        + CommonKit.encryptAndBase64(password)
                        + "','"
                        + nickname
                        + "',?," + gender + ",now(),now())", new Object[]{headimg});
        List<User> _users = jdbctemplate.query(
                "select * from user where uuid=?", new Object[]{uuid},
                new User());
        return getOne(_users);
    }

    /**
     * 根据唯一标识获取用户对象
     */
    public User getUserByToken(String token) {
        List<User> users = jdbctemplate.query("select * from user where username=? or openid=?",
                new Object[]{token, token}, new User());
        return getOne(users);
    }

    /**
     * 根据唯一标识获取用户uuid
     */
    public String getUserUuidByToken(String token) {
        User user = getUserByToken(token);
        if (user == null) {
            return null;
        }
        return user.getUuid();
    }

    /**
     * 本地登录校验
     */
    public User login(String username, String password) {
        List<User> users = jdbctemplate.query(
                "select * from user where username =? and password = ?",
                new Object[]{username, CommonKit.encryptAndBase64(password)},
                new User());
        return getOne(users);
    }

    private User getOne(List<User> users) {
        if (users.size() == 0) {
            return null;
        }
        return users.get(0);
    }


    public boolean updateUser(User user) {
        if (user == null) {
            return false;
        }
        String password = user.getPassword();
        String nickname = user.getNickname();
        byte[] headimg = user.getHeadimg();
        String sql = "";
        if (StringUtils.hasLength(password)) {
            sql += ",password='" + password + "'";
        }
        if (StringUtils.hasLength(nickname)) {
            sql += ",nickname='" + nickname + "'";
        }
        if (headimg != null) {
            sql += ",headimg='" + headimg + "'";
        }
        if (StringUtils.isEmpty(sql)) {
            return false;
        }
        return jdbctemplate.update("update user set " + sql.replaceFirst(",", "") + " where uuid = ?", user.getUuid()) > 0;
    }
}
